import { uuid } from '@/utils'
import type { TableColumn } from '@/types'
import { PAGING } from '@/constant'
import { ElLink } from 'element-plus'
import { loadGatewayListByPage, deleteGateway, getStatisticsData, exportGatewayInfo } from '@/api/modules/gateway'

export const REG_EXP_IP = /^((25[0-5]|2[0-4]\d|[01]?\d{1,2})\.){3}(25[0-5]|2[0-4]\d|[01]?\d{1,2})$/

export interface GatewayInfo {
  /** 网关编号 */
  gatewayNumber: string
  /** 网关名称 */
  gatewayName: string
  /** 规格型号 */
  gatewayModel: string
  /** 生产厂家 */
  gatewayManufacturer: string
  /** 安装位置 */
  gatewayLocation: string
  /** 安装厂家 */
  gatewayInstallManufacturer: string
  /** 安装时间 */
  gatewayInstallTime: string
  /** 安装方式 */
  gatewayInstallWay: string
  /** 运行状态 */
  gatewayStatus: string | number
  gatewayStatusName?: string
  /** 状态发生时间 */
  gatewayStatusTime: string
  /** IP地址 */
  gatewayIp: string
  /** 计量器具数量 */
  gatewayMeasurementNumber?: number
  /** 采集测点数量 */
  gatewayCollectPointNumber?: number
  [key: string]: any
}

export const defaults: GatewayInfo = {
  gatewayNumber: '',
  gatewayName: '',
  gatewayModel: '',
  gatewayManufacturer: '',
  gatewayLocation: '',
  gatewayInstallManufacturer: '',
  gatewayInstallTime: '',
  gatewayInstallWay: '',
  gatewayStatus: '1',
  gatewayStatusTime: '',
  gatewayIp: '',
}

export function useTableData(
  callback1?: (row: GatewayInfo) => void,
  callback2?: (row: GatewayInfo) => void,
) {
  const columns = shallowRef<TableColumn<GatewayInfo>[]>([
    { key: uuid(), label: '网关编号', prop: 'gatewayNumber' },
    { key: uuid(), label: '网关名称', prop: 'gatewayName' },
    { key: uuid(), label: '规格型号', prop: 'gatewayModel' },
    { key: uuid(), label: '安装位置', prop: 'gatewayLocation' },
    { key: uuid(), label: 'IP地址', prop: 'gatewayIp' },
    { key: uuid(), label: '运行状态', prop: 'gatewayStatusName' },
    {
      key: uuid(),
      label: '计量器具数量',
      prop: 'gatewayMeasurementNumber',
      render({ row }) {
        return h(
          ElLink,
          {
            type: 'primary',
            onClick: () => {
              callback1?.(row)
            },
          },
          () => row.gatewayMeasurementNumber,
        )
      },
    },
    {
      key: uuid(),
      label: '采集测点数量',
      prop: 'gatewayCollectPointNumber',
      render({ row }) {
        return h(
          ElLink,
          {
            type: 'primary',
            onClick: () => {
              callback2?.(row)
            },
          },
          () => row.gatewayCollectPointNumber,
        )
      },
    },
  ])
  const [loading, setLoading] = useState(false)
  const [tableData, setTableData] = useShallowState<GatewayInfo[]>([])
  const pagination = reactive({
    pageNumber: 1,
    pageSize: PAGING.PAGE_SIZES[0]!,
    total: 0,
  })

  const [totalGatewayNumber, setTotalGatewayNumber] = useState(0)
  const [totalIndicatorNumber, setTotalIndicatorNumber] = useState(0)
  const [totalToolsNumber, setTotalToolsNumber] = useState(0)

  async function confirmDel() {
    return ElMessageBox.confirm(
      '确认要删除该网关吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
  }
  async function getLists(params: any) {
    setLoading(true)
    try {
      const { data } = await loadGatewayListByPage(
        params.pageNumber,
        params.pageSize,
      )
      const mapFn: (v: any) => GatewayInfo = (v: any) => {
        return {
          id: v.id,
          gatewayNumber: v.number,
          gatewayName: v.name,
          gatewayModel: v.model,
          gatewayManufacturer: v.manufacturer,
          gatewayLocation: v.installLocation,
          gatewayInstallManufacturer: v.installManufacturer,
          gatewayIp: v.ipAddress,
          gatewayStatus: v.status,
          gatewayStatusName: v.statusName,
          gatewayStatusTime: v.statusDate,
          gatewayInstallTime: v.installDate,
          gatewayInstallWay: v.installWay,
          gatewayMeasurementNumber: v.toolsNum,
          gatewayCollectPointNumber: v.indicatorNum,
        }
      }
      setTableData(
        (data.records || []).map(mapFn),
      )
      pagination.total = data.total
    }
    catch (e) {
    }
    finally {
      setLoading(false)
    }
  }

  async function del(gatewayId?: number) {
    const res = await confirmDel().catch(() => {})
    if (res !== 'confirm' || !gatewayId)
      return false
    try {
      await deleteGateway(gatewayId)
      ElMessage.success('删除成功')
      return true
    }
    catch (e) {}
  }

  async function getStatisticalData() {
    try {
      const { data } = await getStatisticsData()
      setTotalGatewayNumber(data.gatewayNumber ?? 0)
      setTotalIndicatorNumber(data.indicatorNumber ?? 0)
      setTotalToolsNumber(data.toolsNumber ?? 0)
    }
    catch (e) {}
  }

  async function downloadExcel() {
    try {
      const { data } = await exportGatewayInfo()
      if (data.url) {
        window.open(data.url)
      }
    }
    catch (e) {}
  }

  return {
    columns,
    tableData,
    pagination,
    loading,
    totalGatewayNumber,
    totalIndicatorNumber,
    totalToolsNumber,
    getLists,
    del,
    getStatisticalData,
    downloadExcel,
  }
}
